// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({env: 'yyf-1gde92y2b5d3dfd2'})

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.action) {
    case 'canteenRankingList': {  //餐厅排行榜 // 数据不合适
      return await canteen_ranking_list(event)
    }
    case 'mealRankingList': {  //饭菜排行榜 // 数据不合适
      return await meal_ranking_list(event)
    }
    case 'mealRankingList2': {  //金牌推荐 // 数据不合适
      return await meal_ranking_list2(event)
    }
    case 'studentRankingList': {  //个人排行榜 // 数据不合适
      return await student_ranking_list(event)
    }
    case 'editStudent':{ // 添加、编辑学生信息   // 通过测试
      return await edit_student(event)
    }
    case 'studentById':{ // 通过学号查询学生信息   // 测试通过
      return await studentById(event)
    }
    case 'oftenBuyMeal':{ // 我经常购买的饭菜   // 通过测试
      return await often_buy_meal(event)
    }
    case 'orderInfoCount':{ // 我的订单统计   // 测试通过
      return await order_info_count(event)
    }
    case 'mealByCondition':{ // 搜索框可以根据餐厅名或者菜名搜索菜list   // 测试通过
      return await meal_by_condition(event)
    }
    default: {  //其他默认返回空，没有数据
      return
    }
  }
}

// 搜索框搜索
async function meal_by_condition(event){
  const db = cloud.database()
  const _ = db.command
  return cloud.database().collection("meal")
  .where(_.and([
    { meal_status:true},
    _.or([
      {
        meal_name:cloud.database().RegExp({
          //以meal_name为关键字进行匹配
          regexp: ".*" + event.value + ".*",
          //输入框输入的内容
          options: 'i',
          //大小写不区分
          })
      },
      {
        canteen:{
          canteen_name :cloud.database().RegExp({
            //以 cnateen_name为关键字进行匹配
            regexp: ".*" + event.value + ".*",
            //输入框输入的内容
            options: 'i',
            //大小写不区分
            })
        } 
      }
    ])
  ]))
  .get()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 餐厅排行榜 
async function canteen_ranking_list(event) {
  return cloud.database().collection("canteen")
  .orderBy('canteen_week_count','desc')
  .limit(event.limit)
  .get()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 饭菜排行榜
async function meal_ranking_list(event) {
  return cloud.database().collection("meal")
  .orderBy('meal_week_count','desc')
  .limit(event.limit)
  .get()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 金牌推荐 
async function meal_ranking_list2(event) {
  return cloud.database().collection("meal")
  .where({
    meal_status:true
  })
  .orderBy('meal_totle_count','desc')
  .limit(event.limit)
  .get()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 个人排行榜
async function student_ranking_list(event) {
  return cloud.database().collection("student")
  .orderBy('student_week_count','desc')
  .limit(event.limit)
  .get()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 添加、编辑学生信息
async function edit_student(event) {
  // 学生信息不存在则添加，存在则更新
 var a = await studentById(event)
  if (a.data.length == 0){
    return cloud.database().collection("student")
    .add({
      data: {
        student_name: event.student_name,
        student_id: event.student_id,
        student_school: event.student_school,
        student_phone: event.student_phone
      }
    })
    .then(res => {
      return res
    })
    .catch(err => {
      return err
    });
  }else{
    return cloud.database().collection("student")
    .where({
      student_id:event.student_id
    })
    .update({
      data: {
        student_name: event.student_name,
        student_id: event.student_id,
        student_school: event.student_school,
        student_phone: event.student_phone
      }
    })
    .then(res => {
      return res
    })
    .catch(err => {
      return err
    });
  }
}
// 通过学号查询学生信息
async function studentById(event) {
  return cloud.database().collection("student")
  .where({
    student_id:event.student_id
  })
  .get()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 我经常购买的饭菜
async function often_buy_meal(event) {
  const db = cloud.database()
  const $ = db.command.aggregate
  return cloud.database().collection("order_info")
  .aggregate()
  .match({
    student:{
      id:event.student_id
    } 
  })
  .group({
    _id: '$meal.id',
    num: $.sum(1)
  })
  .sort({
    num:-1
  })
  .lookup({
    from: "meal",
    localField: "_id",
    foreignField:"_id",
    as: "meal"
  })
  .limit(event.limit)
  .end()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}
// 我的订单统计
async function order_info_count(event) {

  const db = cloud.database()
  const $ = db.command.aggregate
  return cloud.database().collection("order_info")
  .aggregate()
  .match({
    student:{
      id:event.student_id
    } 
  })
  .group({
    _id: '$order_status',
    num: $.sum(1)
  })
  .end()
  .then(res => {
    return res
  })
  .catch(err => {
    return err
  });
}